#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
    File Name:      dimen_generate_utils
    Author:         'daze'
    date:           2018/12/4
    description:    解决的问题：在标准分辨率的下如果不开发的话可以使用 map_x() 动态适配，可是如果新加坐标，之前是判断如果不是标准分辨率就转换（但是应该不转换）
    导致新加的不改转换的坐标反而转换了，不准
"""
import os
import AutoWool.main.utils.dj_single_use_utils
import pyautogui
import xml.etree.ElementTree as ET

from AutoWool.main.config.config_utils import ConfigUtils
from AutoWool.main.utils.adb_utils import AdbUtils
from AutoWool.main.utils.log_utils import Log

target_dimen_list = [(1920, 1080), (1366, 768), (2560, 1440), (1440, 720)]

standard_pc_screen_w = 1920
standard_pc_screen_h = 1080
standard_phone_screen_w = 1080  # 720      # 默认夜神的分辨率：
standard_phone_screen_h = 1920  # 1280
cur_pc_screen_w, cur_pc_screen_h = pyautogui.size()
cur_phone_screen_w, cur_phone_screen_h = AdbUtils.get_phy_w(), AdbUtils.get_phy_h()

dimen_dir = os.path.join(ConfigUtils.Dir.get_cur_workspace_project_abs_path(), 'dimen\\')


class DimenUtils:

    @staticmethod
    def __get_x_file_path(dimen_dir_abs_path):
        return os.path.join(dimen_dir_abs_path, 'x.xml')

    @staticmethod
    def __get_y_file_path(dimen_dir_abs_path):
        return os.path.join(dimen_dir_abs_path, 'y.xml')

    '''用来生成 dimen 目录'''

    @staticmethod
    def gen_dimens():
        for dimen_tuple in target_dimen_list:
            target_w = dimen_tuple[0]
            target_h = dimen_tuple[1]
            if target_w < target_h:
                raise Exception('生成 dimen 目录的 target_dimen_list 必须宽比高大')
            dimen_dir_abs_path = os.path.join(dimen_dir, str(target_w) + '_' + str(target_h))
            if not os.path.exists(dimen_dir_abs_path):
                os.mkdir(dimen_dir_abs_path)
            # 创建x.xml 和 y.xml
            x_dimen_abs_path = DimenUtils.__get_x_file_path(dimen_dir_abs_path)
            y_dimen_abs_path = DimenUtils.__get_y_file_path(dimen_dir_abs_path)
            with open(x_dimen_abs_path, 'w') as f:
                f.write('<resources>\n')
                for i in range(standard_pc_screen_w):
                    valuex = int(target_w / standard_pc_screen_w * i)
                    f.write('   <dimen name="px_' + str(i) + '">' + str(valuex) + '</dimen>\n')
                f.write('   <dimen name="px_' + str(standard_pc_screen_w) + '">' + str(target_w) + '</dimen>\n')
                f.write('</resources>')
            with open(y_dimen_abs_path, 'w') as f:
                f.write('<resources>\n')
                for i in range(standard_pc_screen_h):
                    valuey = int(target_h / standard_pc_screen_h * i)
                    f.write('   <dimen name="px_' + str(i) + '">' + str(valuey) + '</dimen>\n')
                f.write('   <dimen name="px_' + str(standard_pc_screen_h) + '">' + str(target_h) + '</dimen>\n')
                f.write('</resources>')

    '''用来适配手机'''

    # 手机标准为：1080px x 1920px，正好和电脑反着
    # 全部转换为 1080x1920,主要用来保证在使用不同手机开发时显示一致效果
    @staticmethod
    def trans_phone_dimen_to_standard() -> ():
        input_str = input('请输入手机分辨率，格式:1920x1080 或 1920_1080,必须从 dimen 目录中选一个,输入回车则使用当前手机分辨率')
        split_array = None
        if input_str.find('x') != -1:
            split_array: str = input_str.split('x')
        elif input_str.find('_') != -1:
            split_array: str = input_str.split('_')
        elif input_str == '':
            split_array = cur_phone_screen_h, cur_phone_screen_w
        else:
            Log.error('trans_phone_dimen_to_standard 输入格式错误')
        phone_screen_w = int(split_array[1])
        phone_screen_h = int(split_array[0])
        cur_x = input('请输入要转换非标准的手机 x 坐标：')
        cur_y = input('请输入要转换非标准的手机 y 坐标：')
        trans_stand_x = int(standard_phone_screen_w / phone_screen_w * int(cur_x))
        trans_stand_y = int(standard_phone_screen_h / phone_screen_h * int(cur_y))
        Log.log('转换后的标准手机分辨率 x 坐标为: ' + str(trans_stand_x))
        Log.log('转换后的标准手机分辨率 y 坐标为: ' + str(trans_stand_y))
        return trans_stand_x, trans_stand_y

    @staticmethod
    def map_x_phone(to_trans_standard_x):
        return DimenUtils.map_y(to_trans_standard_x, True)

    @staticmethod
    def map_y_phone(to_trans_standard_y):
        return DimenUtils.map_x(to_trans_standard_y, True)

    '''用来适配电脑'''

    # 转换非标准的坐标到标准坐标，主要用来适配电脑时，在非 1920, 1080 分辨率的电脑开发，需要先转换成标准坐标
    @staticmethod
    def trans_pc_dimen_to_standard() -> ():
        cur_x = input('请输入要转换非标准的 x 坐标：')
        cur_y = input('请输入要转换非标准的 y 坐标：')
        if standard_pc_screen_w == cur_pc_screen_w:
            trans_stand_x = cur_x
            trans_stand_y = cur_y
            Log.log('转换后的标准 x 坐标为: ' + str(cur_x))
            Log.log('转换后的标准 y 坐标为: ' + str(cur_y))
        else:
            trans_stand_x = int(standard_pc_screen_w / cur_pc_screen_w * int(cur_x))
            trans_stand_y = int(standard_pc_screen_h / cur_pc_screen_h * int(cur_y))
            Log.log('转换后的标准 x 坐标为: ' + str(trans_stand_x))
            Log.log('转换后的标准 y 坐标为: ' + str(trans_stand_y))
        return trans_stand_x, trans_stand_y

    # 映射坐标x  注意：传入的必须是标准坐标 1920x1080 里的，否则没法适配
    @staticmethod
    def map_x(to_trans_standard_x, is_phone=False) -> int:
        if standard_pc_screen_w == cur_pc_screen_w and is_phone is False:
            return to_trans_standard_x
        if is_phone:
            target_dimen_dir_name = str(cur_phone_screen_h) + '_' + str(cur_phone_screen_w)
        else:
            target_dimen_dir_name = str(cur_pc_screen_w) + '_' + str(cur_pc_screen_h)
        target_dimen_dir_abspath = os.path.join(dimen_dir, target_dimen_dir_name)
        if not os.path.exists(target_dimen_dir_abspath):
            raise Exception('生成的dimen目录 ' + target_dimen_dir_abspath + ' 不存在! ')
        x_dimen_abs_path = DimenUtils.__get_x_file_path(target_dimen_dir_abspath)
        xml_tree = ET.ElementTree(file=x_dimen_abs_path)
        xml_key = "px_" + str(to_trans_standard_x)
        xml_value = 0
        for elem in xml_tree.iter():
            # Log.log('elem.attrib=' + str(elem.attrib))
            if len(elem.attrib) != 0:
                if elem.attrib['name'] == xml_key:
                    xml_value = elem.text
        return xml_value

    # 映射坐标y
    @staticmethod
    def map_y(to_trans_standard_y, is_phone=False) -> int:
        if standard_pc_screen_h == cur_pc_screen_h and is_phone is False:
            return to_trans_standard_y
        if is_phone:
            target_dimen_dir_name = str(cur_phone_screen_h) + '_' + str(cur_phone_screen_w)
        else:
            target_dimen_dir_name = str(cur_pc_screen_w) + '_' + str(cur_pc_screen_h)
        target_dimen_dir_abspath = os.path.join(dimen_dir, target_dimen_dir_name)
        if not os.path.exists(target_dimen_dir_abspath):
            raise Exception('生成的dimen目录 ' + target_dimen_dir_abspath + ' 不存在! ')
        y_dimen_abs_path = DimenUtils.__get_y_file_path(target_dimen_dir_abspath)
        xml_tree = ET.ElementTree(file=y_dimen_abs_path)
        xml_key = "px_" + str(to_trans_standard_y)
        xml_value = 0
        for elem in xml_tree.iter():
            # Log.log('elem.attrib=' + str(elem.attrib))
            if len(elem.attrib) != 0:
                if elem.attrib['name'] == xml_key:
                    xml_value = elem.text
        return xml_value
